package com.smart.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smart.dao.LoginDao;
import com.smart.domain.Login;
import com.smart.domain.User;
import com.smart.service.LoginService;
import com.smart.service.UserService;
import com.smart.tools.DESHelper;
import com.smart.tools.DateHelper;
import com.smart.tools.MessageException;
import com.smart.tools.ObjectHelper;

@Service
public class LoginServiceImpl  implements LoginService{

	@Autowired
	UserService userService;

	@Autowired
	LoginDao loginDao;

	@Override
	@Transactional
	public Login toLogin(String userName, String password , String loginDevice , String loginIp) throws Exception {
		//根据用户名获取用户信息
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("userName", userName);
		User  user = userService.findbyCons(conditions);
		
		//如果为空 根据手机号获取
		if(ObjectHelper.isEmpty(user)){
			conditions = new HashMap<String, Object>();
			conditions.put("phoneNumber", userName);
			 user = userService.findbyCons(conditions);
		}
		
		if(ObjectHelper.isEmpty(user)){
			throw new MessageException("无效用户");
		}
		
		//验证密码
		//比较是否一致
		if(user.getPassword().equals(password)){
			//如果需要支持单点登录直接删掉之前的登录信息 ,并记录登录日志  TODO
			//生成登录数据
			Login login = new Login();
			login.setLoginDevice(loginDevice);
			login.setLoginIp(loginIp);
			String date = DateHelper.dateToString(new Date());
			login.setLoginTime(date);
			login.setToken(DESHelper.getInstance().encrypt(date));
			return  loginDao.saveEntity(login);
		}
		
		
		return null;
	}

	@Override
	public Login findByCond(Map<String, Object> conditions) throws Exception {
			List<Login> logins = loginDao.queryLogin(conditions);
			if(ObjectHelper.isNotEmpty(logins) && logins.size() != 0){
				return logins.get(0);
			}
			
		return null;
	}

	@Override
	@Transactional
	public void logout(Login login) throws Exception {
		if(ObjectHelper.isNotEmpty(login.getToken())){
			loginDao.deleteEntity(login);
			//记录登录日志 TODO
		}
		return ;
	}
	
}
